import 'dart:collection';

import 'core.dart';
import 'interpreter.dart';

/**
 *   PACKAGE:
 *   USER:Administrator
 *   TIME:2021/1/14 0014 23:58
 *   Description:工具函数，变量，debug等
 */

/**
 * 函数搜索，根据包名和函数名搜索
 */
FunctionDefinition search_function(String package,String identifier) {
  FunctionDefinition functionDefinition = null;
  Interpreter.getInstance().module[package].function_list.forEach((entry) {
      if (entry.name == identifier) {
        functionDefinition = entry;
      }
  });
  ///如果当前模块没有再搜索core模块
  if(functionDefinition!=null) return functionDefinition;
  Interpreter.getInstance().module["cool.core"].function_list.forEach((entry) {
    if (entry.name == identifier) {
      functionDefinition = entry;
    }
  });
  return functionDefinition;
}

Value search_local_variable(
    LinkedList<Variable> localEnvironment, String identifier) {
  Value ve = null;
  localEnvironment?.forEach((v) {
    if (v.name == identifier) {
      {
        ve = v.value;
      }
    }
  });
  return ve;
}
Value search_global_variable(String module,String identifier) {
  Value ve = null;
  Interpreter.getInstance().module[module]?.variable?.forEach((v) {
    if (v.name == identifier) {
      ve = v.value;
    }
  });
  return ve;
}

void search_and_add_variable(LinkedList<Variable> localEnvironment, String module, Expression left, Value return_value,bool isFixed) {
  bool exit = false;

  ///是否有本地环境，有的话是不能添加全局变量的,另外数组表达式在此只能修改
  if(localEnvironment == null){
    Interpreter.getInstance().module[module].variable.forEach((entry) {
      if (entry.name == left.identifier) {

        if(!entry.isFixed) {
          ///是否允许修改
          entry.value = return_value;
        }
        else{
          print("警告:${entry.name}不可修改");
        }
        exit = true;
      }
    });
    if (exit) return;
    Interpreter.getInstance().module[module].variable.add(Variable(left.identifier, return_value,isFixed));
  }else{
    localEnvironment?.forEach((entry) {
      if(entry.name == left.identifier){
        if(!entry.isFixed) {
          ///是否允许修改
          entry.value = return_value;
        }
        else{
          print("局部变量,警告:${entry.name}不可修改");
        }
        exit = true;
      }
    });
    if (exit) return;
    localEnvironment.add(Variable(left.identifier,return_value,isFixed));
  }

}